// get record in  mongodb and rds db.
// first to get in mongodb.

package empower

import (
	conf "config"
	"errors"
	"github.com/extrame/goblet"
	"log"
	"time"
)

type EmpowerForm struct {
	IdCode       string
	UserName     string
	IdName       string
	FromName     string
	FromUserName string
	FromUserId   string
	Empowertype  []EmpowerType
	Content      string
	CreateDate   time.Time
	UpdateDate   time.Time
	IsDelete     bool
	Uuid         string `xorm:"-" json:"-"`
}

//  授权类型
type EmpowerType struct {
	Code     string
	Category string
	Name     string
	RzStatus string
	Status   bool
	Shared   bool
	Key      string
	DataId   string
}

func Getrecord(idcode, fromid string) (*EmpowerForm, error) {
	record := new(EmpowerForm)
	if conf.Config.UseMongodb {
		return record, nil
	}
	exist, err := goblet.DB.Where("`id_code`= ? and from_user_id= ?", idcode, fromid).Get(record)
	if exist {
		return record, err
	} else if err != nil {
		log.Println("getrecord_err:", err, record)
		return nil, err

	}
	return nil, errors.New("not_found")
}

func Putrecord(record *EmpowerForm) error {
	// putrecord into mongoDB.

	if exist, _ := goblet.DB.Where("id_code= ? and `from_user_id`= ?", record.IdCode, record.FromUserId).Get(new(EmpowerForm)); exist {
		return Updaterecord(record)
	}
	record.CreateDate = time.Now()
	_, err := goblet.DB.Insert(record)
	return err
}
func Updaterecord(record *EmpowerForm) error {
	record.UpdateDate = time.Now()
	if _, err := goblet.DB.Where("id_code= ? and from_user_id= ?", record.IdCode, record.FromUserId).Cols("id_name", "from_name", "from_user_name", "empowertype", "content", "update_date").Update(record); err != nil {
		return err
	}
	return nil
}
func Delrecord(idcode, from_id string) error {
	_, err := goblet.DB.Where("id_code= ? and from_user_id= ?", idcode, from_id).Delete(new(EmpowerForm))
	if err != nil {
		return err
	}
	return nil
}
func GetEnterpriseUuid(appid string) string {
	type enterprise struct {
		Uuid string
	}
	enter := new(enterprise)
	if appid != "" {
		if exist, err := goblet.DB.Where("appid= ?", appid).Get(enter); !exist || err != nil {
			return enter.Uuid
		}
	}
	return ""
}
